﻿Imports MySql.Data.MySqlClient
Public Class Laucher
    Private log As ActivityLogger
    Private cumulerror As String
    Dim myh As MySqlHandler
    Dim wch As IWinccHandler
    Dim ewser As EwinSyncService
    Dim service As EwinsynServiceHandler
    Dim isloaded As Boolean
    Dim isswhowing As Boolean
    Private Sub btnsetting_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsetting.Click
        Dim frm As New Settings
        'frm.loadConfiguration()
        frm.ShowDialog(Me)
    End Sub

   

    Private Sub Launcher_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        'log.log(commons.MOD_APPSELF, "Application exit", ActivityLoggerConf.LOGLEVEL_INFO)
        'log.closeLog()
    End Sub

    
    Private Sub Launcher_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'Me.Visible = False
        'Debug.Print("in load set visible to false")
        launchtimer.Enabled = True
        launchtimer.Start()
    End Sub
    
    Private Sub launchtimer_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles launchtimer.Tick
        launchtimer.Stop()
        launchtimer.Enabled = False
        initWork()
        launcherctm.Enabled = True
        isloaded = True
        'Me.WindowState = FormWindowState.Minimized
    End Sub
    Private Sub initWork()
        log = ActivityLogger.getInstance()
        checkServiceStatus()
        
    End Sub
    Private Sub checkServiceStatus()
        If (IsNothing(service)) Then service = EwinsynServiceHandler.getInstance
        If (service.getServiceStatus = EwinsynServiceHandler.SERVICE_STARTED Or service.getServiceStatus = EwinsynServiceHandler.SERVICE_STARTING) Then
            btnstart.Enabled = False
            btnrestart.Enabled = True
            btnstop.Enabled = True
            btnsetting.Enabled = False
            btnmap.Enabled = False
        Else
            btnstart.Enabled = True
            btnsetting.Enabled = True
            btnmap.Enabled = True
            btnrestart.Enabled = False
            btnstop.Enabled = False
        End If
        If (service.getServiceStatus = EwinsynServiceHandler.SERVICE_ERROR) Then
            doErrors()
        End If
    End Sub

    Private Sub btnmap_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnmap.Click
        Dim frm As New mappingform
        frm.ShowDialog(Me)
    End Sub

    Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
        Dim frm As New Logsandstats
        frm.ShowDialog(Me)
    End Sub

    Private Sub doErrors()
        lnkerror.Visible = True
        cumulerror = service.getErrors
    End Sub
    Private Sub btnstart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnstart.Click
        'log.log(commons.MOD_APPSELF, "Starting Service", ActivityLoggerConf.LOGLEVEL_INFO)
        'startService()
        commons.startService()
        checkServiceStatus()
    End Sub
    Private Sub startService()
        'Dim ret As Integer = service.startService

        ' Select Case ret
        '    Case EwinsynServiceHandler.SERVICE_ERROR
        'doErrors()
        '    Case EwinsynServiceHandler.SERVICE_STARTED
        ' btnstart.Enabled = False
        'End Select

        'myh = MySqlHandler.getInstance
        'cumulerror = ""
        'lnkerror.Visible = False
        ''check mysql database. if not true log and exit and show error link
        'If (Not checkMysqlDatabase()) Then
        '    cumulerror = "Service not started due to the following reasons" + vbCrLf + cumulerror
        '    lnkerror.Visible = True
        '    sysevt.WriteEntry(cumulerror)
        '    Return
        'End If
        ''check winccdatabase

        'wch = getWinCCHandler()
        'If (Not checkWinCc()) Then
        '    cumulerror = "Service not started due to the following reasons" + vbCrLf + cumulerror
        '    lnkerror.Visible = True
        '    sysevt.WriteEntry(cumulerror)
        '    Return
        'End If
        ''check table mapping
        'Dim tm As ewindt.DtTableMappingDataTable = myh.getTablesMapping
        'Dim cm As ewindt.DtColumnMappingDataTable = myh.getColumnMapping
        'If (IsNothing(tm)) Then
        '    tm = New ewindt.DtTableMappingDataTable
        '    cm = New ewindt.DtColumnMappingDataTable
        'End If
        'If (Not checkMapping(tm, cm)) Then
        '    cumulerror = "Service not started due to the following reasons" + vbCrLf + cumulerror
        '    lnkerror.Visible = True
        '    sysevt.WriteEntry(cumulerror)
        '    Return
        'End If
        ''check if the tables exist and have the same value
        'If (Not myh.checkAnCompareMapping(tm, cm)) Then
        '    'add cumulative error and return
        '    cumulerror = "Service not started due to the following reasons" + vbCrLf + myh.Errors
        '    lnkerror.Visible = True
        '    sysevt.WriteEntry(cumulerror)
        '    Return
        'End If
        ''enable timer
        'ewser = New EwinSyncService(myh, wch)
        'launch()
    End Sub
    Private Sub launch()
        Dim nextl As DateTime = Now.AddMinutes(My.Settings.op_importdelay)
        doLog("Launch Timer started and will fire at " + nextl.ToString("hh:mm:ss"), ActivityLoggerConf.LOGLEVEL_INFO)
        mocklauncher.Enabled = True
        mocklauncher.Start()
        'My.Application.DoEvents()
    End Sub
    Private Sub stopService()

    End Sub
    Private Sub restartService()
        stopService()
        startService()
    End Sub
    Private Function checkMapping(ByRef tm As ewindt.DtTableMappingDataTable, ByRef cm As ewindt.DtColumnMappingDataTable) As Boolean
        If (tm.Rows.Count <= 0) Then
            doCumulativeError("There are no Mapping with WinCC database defined yet. Please set the mapping before running the service", ActivityLoggerConf.LOGLEVEL_OPERATION)
            Return False
        End If

        For Each tr As ewindt.DtTableMappingRow In tm.Rows
            Dim filter As String = cm.idtablemappingColumn.ColumnName + "=" + tr.id.ToString
            Dim cr() As ewindt.DtColumnMappingRow = cm.Select(filter)
            If (cr.Length <= 0) Then
                doCumulativeError("One or more tables are not correctly mapped. Please set the mapping before running the service", ActivityLoggerConf.LOGLEVEL_OPERATION)
                Return False
            End If
        Next
        Return True
    End Function
    Private Function checkWinCc() As Boolean
        If (Not wch.testconnection) Then
            doCumulativeError("WinCC server at " + wch.WConfig.Datasource + " is not reacheable due to" + wch.Errors, ActivityLoggerConf.LOGLEVEL_ERROR)
            Return False
        End If
        Return True
    End Function
    Private Function checkMysqlDatabase() As Boolean
        Dim mu As New MySqlUtilities(MySqlHandler.getInstance().mysqlconf)
        If (Not mu.databaseExist) Then
            If (mu.MysqErrorcode = MySqlErrorCode.UnknownDatabase) Then
                If (Not My.Settings.resetmysql) Then
                    doCumulativeError("Database " + mu.mysqldb + " not found on the specified Adress. Please verify Setting and check 'Reset database' to install it into the specified server", ActivityLoggerConf.LOGLEVEL_ERROR)
                    Return False
                Else
                    If (Not myh.installDatabase) Then
                        doCumulativeError("Unable to instal " + mu.mysqldb + " database due to the following error ", ActivityLoggerConf.LOGLEVEL_ERROR)
                        doCumulativeError(vbTab + "" + MySqlHandler.getInstance.Errors, ActivityLoggerConf.LOGLEVEL_ERROR)
                        Return False
                    Else

                        My.Settings.resetmysql = False
                    End If
                End If
            Else
                Return False
            End If
        End If
        Return True
    End Function
    Private Sub doLog(ByVal msg As String, ByVal svt As String)
        log.log(commons.MOD_APPSELF, msg, svt)
    End Sub
    Private Sub doCumulativeError(ByVal msg As String, ByVal svt As String)
        cumulerror = cumulerror + vbCrLf + "- " + msg + "(" + svt + ")"
        doLog(msg, svt)
    End Sub

    Private Sub lnkerror_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles lnkerror.LinkClicked
        Dim dlg As New ErrorDisplay
        dlg.txterr.Text = cumulerror
        dlg.ShowDialog(Me)
    End Sub
    Private Function getWinCCHandler() As IWinccHandler
        If (My.Settings.op_isdebug) Then
            Return MockWinccHandler.getInstance
        End If
        Return WinccHandler.getInstance

    End Function

    Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
        Me.Close()
    End Sub

    Private Sub mocklauncher_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles mocklauncher.Tick
        mocklauncher.Stop()
        mocklauncher.Enabled = False
        doLog("import starting", ActivityLoggerConf.LOGLEVEL_INFO)
        StartImport()
    End Sub
    Private Sub StartImport()
        Dim sstart As Object = myh.getLastWinccSync
        Dim start As DateTime = Now.AddMinutes(-1 * My.Settings.op_importdelay)
        If (Not IsNothing(sstart)) Then
            start = CType(sstart, DateTime)
        End If
        Dim endi As DateTime = Now
        ewser.performImport(start, endi)
        myh.updateLastWinccSync(endi)
        mocklauncher.Interval = My.Settings.op_importdelay * 60000
        doLog("import done", ActivityLoggerConf.LOGLEVEL_INFO)
        launch()
    End Sub

    Private Sub ShowSettingToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ShowSettingToolStripMenuItem.Click
        isswhowing = True
        If (Not Me.Visible) Then Me.Visible = True
        If (Not Me.WindowState = FormWindowState.Normal) Then Me.WindowState = FormWindowState.Normal
        Me.Focus()
    End Sub

    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        Me.Close()
    End Sub


    Private Sub Laucher_VisibleChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.VisibleChanged
       
    End Sub

    Private Sub btnstop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnstop.Click
        commons.stopService()
        checkServiceStatus()
    End Sub

    Private Sub btnrestart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnrestart.Click
        commons.restartService()
        checkServiceStatus()
    End Sub
End Class
